/**
 * Module dependencies.
 */

var express = require('express'), routes = require('./routes'), path = require('path'), http = require('http'), formidable = require('formidable'), mongoose = require('mongoose'), WebSocketServer = require('websocket').server;

var schemas = require('./models/models.js')

var app = module.exports = express.createServer();

var wsServer = new WebSocketServer({
	httpServer : app,

	// Firefox 7 alpha has a bug that drops the
	// connection on large fragmented messages
	fragmentOutgoingMessages : false
});

var messageCount = 0;
connections = [];
users = [];
validIDs = new Array();

wsServer.on('request', function(request) {
	var connection = request.accept(null, request.origin);
	connections.push(connection);

	// Handle closed connections
	connection.on('close', function() {
		console.log(connection.remoteAddress + " disconnected");

		var index = connections.indexOf(connection);
		if(index !== -1) {
			// remove the connection from the pool
			connections.splice(index, 1);
			users.splice(index, 1);
			mex = {
				type : "usrOnline",
				message : users
			}

			for(i in connections) {
				connections[i].send(JSON.stringify({
					type : "usrOnline",
					message : users

				}))
			}
		}
	});
	// Handle incoming messages
	connection.on('message', function(message) {

		//console.log(message.utf8Data)
		jObj = JSON.parse(message.utf8Data)
		if(jObj.type == "chat") {
			mex = {
				type : "chat",
				message : message.utf8Data
			}

			for( i = 0; i < connections.length; i++)
			connections[i].send(JSON.stringify(mex))

		} else if(jObj.type == "coop") {
			mex = {
				type : "coop",
				message : message.utf8Data
			}
			for( i = 0; i < connections.length; i++) {
				if(connection != connections[i]) {
					connections[i].send(JSON.stringify(mex))
				}
			}
		} else if(jObj.type == "usrOnline") {

			if(connections.indexOf(jObj.usr) != -1)
				connections.splice(connections.indexOf(jObj.usr), 1)
			users.push(jObj.usr)
			mex = {
				type : "usrOnline",
				message : users
			}
			for( i = 0; i < connections.length; i++) {
				//if(connection != connections[i]) {
				connections[i].send(JSON.stringify(mex))
				//	} else {

				connections[i].send(JSON.stringify({
					type : "usrOnline",
					message : users
				}))

			}

		}
	});
	// Handle closed connections
	connection.on('close', function() {
		console.log(connection.remoteAddress + " disconnected");

		var index = connections.indexOf(connection);
		if(index !== -1) {
			// remove the connection from the pool
			connections.splice(index, 1);
		}
	});
});
sendMessage = function(message) {
	console.log(connections)
	for(i in connections) {
		connections[i].sendUTF(message);
	}
}
// Configuration

app.configure(function() {
	app.set('views', __dirname + '/views');
	app.set('view engine', 'ejs');
	app.use(express.bodyParser());
	app.use(express.methodOverride());
	app.use(app.router);
	//app.use(express.static(__dirname + '/public/projects/'));
	app.use(express.static(__dirname + '/public/html'));
	app.use(express.static(__dirname + '/public'));
})

app.configure('development', function() {
	app.use(express.errorHandler({
		dumpExceptions : true,
		showStack : true
	}));
});

app.configure('production', function() {
	app.use(express.errorHandler());
});
//
//
// Routes
app.get('/user/all', routes.user.userGetAll)//get all the users
app.get('/user/name/all', routes.user.userNamesGetAll)//get all the usernames
app.get('/user', routes.user.userGet)//get a single user
app.post('/user/new', routes.user.createUser)//create a new user
app.del('/user/all', routes.user.userDeleteAll)//delete all users
app.del('/user/del', routes.user.userDelete)//delete a user
app.get('/CodeBubble', routes.codebubble.getIde)//get the IDE homepage
app.get('/sorry', routes.codebubble.getSorry)//get the 'sorry' homepage
app.get('/proj/all', routes.file.getProjectsAll)//to get all the project logs
app.get('/proj/list', routes.file.getProjectsList)//get all projects as a list for the treeview
app.del('/proj/all', routes.file.delProjectsAll)//to delete all project logs
app.post('/proj/save', routes.file.saveFile)//to save a file
app.get('/proj/file', routes.file.getFileCode)//to get the code of a file
app.get('/session', routes.codebubble.getSession)//to get a session
app.post('/proj/savesession', routes.codebubble.saveSession)//save the session!
app.post('/proj', function(req, res) {//upload a project!
	var newProject = mongoose.model('Project', schemas.ProjectSchema);
	var fs = require('fs');
	var sys = require('util');
	var pathname;
	var filename;
	var destination = './public/projects/' + req.query.name + '/';
	var allowedUsers = req.query.users.split(' ')
	fs.mkdirSync(destination, 0777)
	var data = new newProject({
		name : req.query.name,
		users : allowedUsers,
		path : destination,
		type : "proj"
	})
	data.save(function(err) {
		console.log(err);
		/*res.send('error in postProj - save');*/
	})
	var form = new formidable.IncomingForm(), files = [], paths = [];
	form.uploadDir = destination
	form.keepExtensions = 'true'
	form.on('file', function(field, file) {
		pathname = file.path
		filename = file.name
		paths.push({
			path : pathname,
			name : filename
		})
	}).on('end', function() {
	})
	form.parse(req, function(err, fields, files) {
		//console.log(paths)
		for(i in paths) {
			fs.renameSync('./' + paths[i].path, destination + paths[i].name.split('/')[1])
		}
		//res.redirect('back')
		res.send(205)
	});
})

app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
